package com.zx.dsptuneup_cloud.fragment;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.HorizontalScrollView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.base.tools.tools.StringUtils;
import com.gyf.barlibrary.ImmersionBar;
import com.orhanobut.hawk.Hawk;
import com.zx.dsptuneup_cloud.Adapter.MatrixAdapter;
import com.zx.dsptuneup_cloud.Adapter.MatrixInputAdapter;
import com.zx.dsptuneup_cloud.Adapter.MatrixOutputAdapter;
import com.zx.dsptuneup_cloud.App;
import com.zx.dsptuneup_cloud.Base.BaseFragment;
import com.zx.dsptuneup_cloud.Enum.MessageReceiveType;
import com.zx.dsptuneup_cloud.R;
import com.zx.dsptuneup_cloud.Tools.ChannelIndexConvert;
import com.zx.dsptuneup_cloud.Tools.Constant;
import com.zx.dsptuneup_cloud.Tools.EventMessage;
import com.zx.dsptuneup_cloud.Util.Constants;
import com.zx.dsptuneup_cloud.Util.NumberBaseConversionUtil;
import com.zx.dsptuneup_cloud.Util.ToastUtil;
import com.zx.dsptuneup_cloud.activity.MatrixActivity;
import com.zx.dsptuneup_cloud.activity.MatrixVo;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;

public class AudioMatrixFragment extends BaseFragment implements View.OnClickListener, MatrixAdapter.OnDbChangeListener, MatrixInputAdapter.OnInputDbChangeListener, MatrixOutputAdapter.OnOutputDbChangeListener{
    private View rootView;
    @BindView(R.id.matrix_recycler)
    RecyclerView matrix_recycler;
    @BindView(R.id.ic_nav)
    TextView ic_nav;
    @BindView(R.id.input_rel_recyle)
    RecyclerView input_rel_recyle;
    @BindView(R.id.output_rel_recyle)
    RecyclerView output_rel_recyle;
    @BindView(R.id.output_hsv)
    HorizontalScrollView output_hsv;
    @BindView(R.id.matrix_hsv)
    HorizontalScrollView matrix_hsv;

    private int groupId = -1;
    private List<MatrixVo> matrixlist;
    private List<MatrixVo> matrixInputlist = new ArrayList<>();      // 输入 14组数据
    private List<MatrixVo> matrixOutputlist = new ArrayList<>();     // 输出 14组数据
    private List<MatrixVo> matrixcontentlist = new ArrayList<>();     // 中间 14*8 组数据

    private MatrixOutputAdapter matrixOutputAdapter;
    private MatrixInputAdapter matrixInputAdapter;
    private MatrixAdapter matrixAdapter;
    private final String TAG = "MatrixActivity";
    private Runnable runnable;
    private Handler handler;
    private MyReceiver myReceiver;
    private String dataString;
    private String[] inputChanneltName = {"HangMic1","ArrayMic1","HamgMic2","ArrayMic2","HangMic3","ArraryMic3","DesktopMicAnalog","Aux","NeetMeeting","MicHowligBack","ReserveDeskMic","Reserve","DesktopMicDigit","ReserveDigit"};
    private String[] outputChanneltName={"Output_AEC","OutputNetMeetin","OutputAMP","OutputMicHowling","OutputMicHowling","OutputReserve2","OutputReserve3","OutputReserve4"};
    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);  IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.RESH_RECEIVER_BROADCAST);
        Log.d("MatrixActivity111","onCreate");
        myReceiver = new MyReceiver();
        //注册广播
       getActivity(). registerReceiver(myReceiver,intentFilter);
       /* if (Hawk.contains("Matrix")){
            dataString=Hawk.get("Matrix");
          //  deviceAudioMatrixInfo( dataString.substring(32,dataString.length()-8));
        }*/

    }
    public AudioMatrixFragment() {
        setFragmentTitle(App.getContext().getString(R.string.matri));
    }
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        Log.d("MatrixActivity222","onCreateView");
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    protected View initView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        if (null != rootView) {
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (null != parent) {
                parent.removeView(rootView);
            }
        } else {
            rootView = inflater.inflate(R.layout.activity_matrix, container, false);
            Log.d("MatrixActivity33333","onCreateView");
            ButterKnife.bind(this, rootView);
            EventBus.getDefault().register(this);
            Log.d("MatrixActivity4444","onCreateView");

        }
        initUI();
       /* if (Hawk.contains("Matrix")){
            dataString=Hawk.get("Matrix");
           // deviceAudioMatrixInfo( dataString.substring(32,dataString.length()-8));

        }*/
        return rootView;
    }

    @Override
    protected void initData() {


    }
    protected void initUI() {
        Log.d("bdfgsfgsg1111","路过~~~~111");
        ImmersionBar.with(this)
                .transparentBar()
                .statusBarColor(R.color.home_bg)
                .statusBarDarkFont(false)
                .init();
    /*    ic_nav.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });*/

        for (int i=0;i<112;i++){
            MatrixVo childDeviceBean = new MatrixVo();
            matrixcontentlist.add(childDeviceBean);
        }
        matrixAdapter = new MatrixAdapter(getActivity(), matrixcontentlist);
        matrix_recycler.setLayoutManager(new GridLayoutManager(getActivity(),8));
        matrix_recycler.setAdapter(matrixAdapter);
        matrixAdapter.setOnDbChangeListener(this);


        for (int i=0;i<14;i++){
            MatrixVo childDeviceBean = new MatrixVo();
            matrixInputlist.add(childDeviceBean);

        }
        matrixInputAdapter = new MatrixInputAdapter(getActivity(),matrixInputlist);
        input_rel_recyle.setLayoutManager(new LinearLayoutManager(getActivity()));
        input_rel_recyle.setAdapter(matrixInputAdapter);
        matrixInputAdapter.setOnDbChangeListener(this);

        for (int i=0;i<8;i++){
            MatrixVo childDeviceBean = new MatrixVo();
            matrixOutputlist.add(childDeviceBean);
        }
        matrixOutputAdapter = new MatrixOutputAdapter(getActivity(),matrixOutputlist);
        output_rel_recyle.setLayoutManager(new GridLayoutManager(getActivity(),8));
        output_rel_recyle.setAdapter(matrixOutputAdapter);
        matrixOutputAdapter.setOnOutputDbChangeListener(this);

        // 绑定recycleView联动
        input_rel_recyle.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    matrix_recycler.scrollBy(dx, dy);
                }
            }
        });
        matrix_hsv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                output_hsv.scrollTo(i, i1);
            }
        });
        //  TODO  sdk>23
        output_hsv.setOnScrollChangeListener(new View.OnScrollChangeListener() {
            @Override
            public void onScrollChange(View view, int i, int i1, int i2, int i3) {
                matrix_hsv.scrollTo(i, i1);
            }
        });

        matrix_recycler.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                if (recyclerView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) {
                    input_rel_recyle.scrollBy(dx, dy);
//                    output_hsv.scrollTo(dx, dy);
                }
            }
        });
    }
    @Override
    protected void initVariables(Bundle bundle) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (myReceiver!=null){
            //取消广播接收者的注册
            getActivity().unregisterReceiver(myReceiver);

        }
    }

    @Override
    public void onClick(View v) {

    }
    /*//处理矩阵数据
    private void  setData(String data){
        initUI();
        Log.d("HomeActivity","路过~~~~");

    }*/
    /**
     * 处理数据
     * */
    private void dealWithVolList(List<MatrixVo> matrixlist) {
        Log.d("bdfgsfgsg2222","路过~~~~");
        if(matrixlist == null || matrixlist.size() < 23){
            ToastUtil.makeText(getActivity(),"音频矩阵数据异常!");
            return;
        }
        matrixInputlist = matrixlist.subList(0,14);
        matrixOutputlist = matrixlist.subList(14,22);
        matrixcontentlist = matrixlist.subList(22,matrixlist.size());
      for (int i=0;i<matrixInputlist.size();i++){
          matrixInputlist.get(i).setChannelName(inputChanneltName[i]);

      }
      for (int i=0;i<matrixOutputlist.size();i++){
          matrixOutputlist.get(i).setChannelName(outputChanneltName[i]);

        }
//        Log.e("111","");
        Log.d("bdfgsfgsg",matrixInputAdapter.toString());
        Log.d("bdfgsfgsg",matrixInputlist.size()+"");
        matrixInputAdapter.setGridViewBeanList(matrixInputlist);
        matrixOutputAdapter.setGridViewBeanList(matrixOutputlist);
        matrixAdapter.setGridViewBeanList(matrixcontentlist);

        for (int i=0;i<matrixInputlist.size();i++){
            Log.d("matrixInputlist","第"+i+"个   "+"gian=="+matrixInputlist.get(i).getGain()+"    type="+matrixInputlist.get(i).getType());
        }
        for (int i=0;i<matrixOutputlist.size();i++){
            Log.d("matrixOutputlist","第"+i+"个   "+"gian=="+matrixOutputlist.get(i).getGain()+"    type="+matrixOutputlist.get(i).getType());
        }
        for (int i=0;i<matrixcontentlist.size();i++){
            Log.d("matrixcontentlist","第"+i+"个   "+"gian=="+matrixcontentlist.get(i).getGain()+"    type="+matrixcontentlist.get(i).getType());
        }
    }



    private void deviceAudioMatrixInfo( String hexData) {
        int num=0;
        ArrayList<MatrixVo> matrixVoList = new ArrayList<>();
        matrixVoList.clear();
        if (!(hexData.length()==804)){
            return;
        }
        boolean isMatrix=false;
        if (Hawk.contains("isMatrix")){
            isMatrix=Hawk.get("isMatrix");
        }
        if (isMatrix){
            return;
        }
    Log.d("HomeActivity长度2==",hexData.length()+"   "+hexData);
        int k = 0;
        int j;
        int outputIndex = 0;  // output
        int inputIndex = 0;  // input
        int indexh = 0;
        for (int h = 0; h <= hexData.length() / 6; h++) {   // h: gain
            MatrixVo matrixVo = new MatrixVo();

            if (h <= 13) {
                inputIndex = inputIndex + 1;
                if (h == 0) {
                    inputIndex = 0;
                }
                outputIndex = 8;
            } else if (13 < h && h <= 21) {
                outputIndex = outputIndex + 1;
                inputIndex = 14;
                if (h == 14) {
                    outputIndex = 0;
                }
            } else {
                outputIndex = outputIndex + 1;
                if (h == 22) {
                    inputIndex = 0;
                    outputIndex = 0;
                }
                if (indexh % 8 == 0 && indexh != 0) {
                    outputIndex = 0;
                    inputIndex = inputIndex + 1;
                }
                indexh = indexh + 1;
            }
            matrixVo.setInput(inputIndex);
            matrixVo.setOutput(outputIndex);
            if (k >= hexData.length()) {
                break;
            }
            j = k + 2;

            String type = hexData.substring(k, j);
            Log.d("bdfgsfgsgtype",type+"num="+num);
            num++;
            matrixVo.setType(Integer.valueOf(NumberBaseConversionUtil.valueHexToValueTen(type)));

            k = j;
            j = k + 4;
            String gain = hexData.substring(k, j);
            Log.d("HomeActivity长度2==2=",gain+"    值为："+NumberBaseConversionUtil.SixToDeciTen(gain));

            matrixVo.setGain(Integer.valueOf(NumberBaseConversionUtil.SixToDeciTen(gain)));
            k = j;

            matrixVoList.add(matrixVo);

        }
        dealWithVolList(matrixVoList);
    }

    @Override
    public void InputDbChange(String db, int position,int type) {
        if(StringUtils.isEmpty(db)){
            ToastUtil.makeText(getActivity(),"请输入db信息!");
            return;
        }
        if(Integer.parseInt(db)>30 || Integer.parseInt(db)<-72 ){
            ToastUtil.makeText(getActivity(),"请输入正确的范围!");
            return;
        }

        int outIndex = position/13;
        MatrixVo matrixVo = matrixInputlist.get(position);
        Log.d("MatrixActivityInput","outIndex=="+outIndex);
        Log.d("MatrixActivityInput","db==="+db+"  position=="+position);
        // http://localhost:8012/device/matrix?input=1&output=1&type=0&gain=45&group=1
        HashMap map = new HashMap();
        map.put("input",matrixVo.getInput());
        map.put("output",matrixVo.getOutput());
        map.put("type",type);
        map.put("gain",Integer.valueOf(db));
        map.put("group",groupId);
        for (int i=0;i<matrixInputlist.size();i++){
            if (position==i){
                matrixInputlist.get(i).setGain(Integer.valueOf(db));
                if (matrixInputAdapter!=null){
                    matrixInputAdapter.notifyDataSetChanged();

                }
            }
Log.d("seting111","第"+i+"个  "+matrixInputlist.get(i).getGain()+"");
        }

        //setMatrixData(map);
        App.getContext().getProtocolServiceUtil().setupDeviceAudioMatrixByGroupNew( matrixVo.getInput(), matrixVo.getOutput(),   type,Integer.valueOf(db));
        Intent intent = new Intent(Constant.updateNum);
        getActivity().sendBroadcast(intent);

    }

    @Override
    public void OutputDbChange(String db, int position,int type) {
        if(StringUtils.isEmpty(db)){
            ToastUtil.makeText(getActivity(),"请输入db信息!");
            return;
        }
        if(Integer.parseInt(db)>30 || Integer.parseInt(db)<-72 ){
            ToastUtil.makeText(getActivity(),"请输入正确的范围!");
            return;
        }
        int outIndex = position/13;
        MatrixVo matrixVo = matrixOutputlist.get(position);
        Log.d("MatrixActivityOutp","outIndex=="+outIndex);
        Log.d("MatrixActivityOutp","db==="+db+"  position=="+position);
        for (int i=0;i<matrixOutputlist.size();i++){
            if (position==i){
                matrixOutputlist.get(i).setGain(Integer.valueOf(db));
                if (matrixOutputAdapter!=null){
                    matrixOutputAdapter.notifyDataSetChanged();

                }
            }
            Log.d("seting222","第"+i+"个  "+matrixOutputlist.get(i).getGain()+"");
        }
        // http://localhost:8012/device/matrix?input=1&output=1&type=0&gain=45&group=1
        HashMap map = new HashMap();
        map.put("input",matrixVo.getInput());
        map.put("output",matrixVo.getOutput());
        map.put("type",type);
        map.put("gain",Integer.valueOf(db));
        map.put("group",groupId);
       // setMatrixData(map);
        App.getContext().getProtocolServiceUtil().setupDeviceAudioMatrixByGroupNew( matrixVo.getInput(), matrixVo.getOutput(),   type, Integer.valueOf(db));
        Intent intent = new Intent(Constant.updateNum);
        getActivity().sendBroadcast(intent);

    }

    @Override
    public void DbChange(String db, int position,int type) {
        if(StringUtils.isEmpty(db)){
            ToastUtil.makeText(getActivity(),"请输入db信息!");
            return;
        }
        if(Integer.parseInt(db)>30 || Integer.parseInt(db)<-72 ){
            ToastUtil.makeText(getActivity(),"请输入正确的范围!");
            return;
        }
        int outIndex = position/13;
        MatrixVo matrixVo = matrixcontentlist.get(position);
        Log.d("MatrixActivityDbCh","outIndex=="+outIndex);
        Log.d("MatrixActivityDbCh","db==="+db+"  position=="+position);
        // http://localhost:8012/device/matrix?input=1&output=1&type=0&gain=45&group=1
        HashMap map = new HashMap();
        map.put("input",matrixVo.getInput());
        map.put("output",matrixVo.getOutput());
        map.put("type",type);
        map.put("gain",Integer.valueOf(db));
        map.put("group",groupId);
        for (int i=0;i<matrixcontentlist.size();i++){
            if (position==i){
                matrixcontentlist.get(i).setGain(Integer.valueOf(db));
                if (matrixOutputAdapter!=null){
                    matrixAdapter.notifyDataSetChanged();

                }
            }
            Log.d("seting333","第"+i+"个  "+matrixcontentlist.get(i).getGain()+"");
        }
       // setMatrixData(map);
        App.getContext().getProtocolServiceUtil().setupDeviceAudioMatrixByGroupNew( matrixVo.getInput(), matrixVo.getOutput(),   type,Integer.valueOf(db));
        Intent intent = new Intent(Constant.updateNum);
        getActivity().sendBroadcast(intent);
    }
    /**
     *  收到消息
     * */
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onGetStickyEvent(EventMessage message) {

    }
    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            //dataString
            if (Hawk.contains("Matrix")){

                dataString=Hawk.get("Matrix");
                Log.d("HomeActivity长度=",dataString.length()+"   数据="+dataString.substring(dataString.length()-8,dataString.length())+"    =?"+ "656e642e".equals(dataString.substring(dataString.length()-8,dataString.length())));

                if ("656e642e".equals(dataString.substring(dataString.length()-8,dataString.length())));{
                    deviceAudioMatrixInfo( dataString.substring(32,dataString.length()-8));
                }
                //deviceAudioMatrixInfo( dataString);
            }


        }
    }
}
